import { defineStore } from 'pinia'

export const useGoodsStore = defineStore('goodsStore', () => {
  const { requestGetNew, requestPostNew } = useRequest()
  const state = reactive({
    curGoodsId: null,
    curSkuId: null,
    curGoodsSkuList: [],
    curGoodsDetail: {} as any,
    recommendGoodsList: [],
    reviewsInfo: {},
    totalReviewsInfo: {},
    reviewsRelatedGoods: [],
  })
  const curGoodsReviews = computed(() => state.curGoodsDetail.reviews ?? [])
  const curGoodsSkuInfo = computed(() => state.curGoodsSkuList.find((item) => item.id === state.curSkuId) ?? {})
  return {
    curGoodsSkuInfo,
    curGoodsReviews,
    ...toRefs(state),
    setGoodsId(goodsId) {
      goodsId && (state.curGoodsId = +goodsId)
    },
    setCurSkuId(curSkuId) {
      curSkuId && (state.curSkuId = +curSkuId)
    },
    async fetchRelatedGoods(goodsId: any) {
      state.reviewsRelatedGoods = await requestGetNew(`/app/goods/getGoodsByGoodsSeries`, { goodsId })
    },
    async getTotalReviewsInfo(goodsId: any) {
      state.totalReviewsInfo = await requestGetNew(`/app/goods/getGoodsReviewOverview`, { goodsId })
    },
    goodsUrlName2GoodsId(goodsUrlName: any) {
      return requestGetNew(`/app/goods/getGoodsIdByGoodsUrlName`, { urlName: goodsUrlName })
    },
    async fetchReviewsList(num, size, goodsId) {
      state.reviewsInfo = await requestGetNew(`/app/reviews/all/${num}/${size}?goodsId=${state.curGoodsId}`, {})
    },
    async initGoodsSkuListByGoodsId() {
      const { curGoodsId } = state
      const [curGoodsSkuList, curGoodsDetail, recommendGoodsList] = await Promise.all([
        requestGetNew(`/app/goods/getSkuByGoodsId?goodsId=${curGoodsId}`, {}),
        requestGetNew(`/app/goods/getGoodsDetail?goodsId=${curGoodsId}`, {}),
        requestGetNew(`/app/goods/getRecommendGoodsByGoodsId?goodsId=${curGoodsId}`, {}),
      ])
      state.curGoodsSkuList = curGoodsSkuList
      state.curGoodsDetail = curGoodsDetail
      state.recommendGoodsList = recommendGoodsList
      state.curSkuId = state.curGoodsSkuList[0]?.id
    },
  }
})
